<?php
/**
 * Created by PhpStorm.
 * User: bzyy
 * Date: 2015/7/4
 * Time: 11:44
 *
 * 处理添加到队里里面的内容
 *
 * 思路步骤：
 * 缓存中读取商品的信息
 * 检测是否已经在队列里面了
 * ajax返回结果
 */

require_once './class/defind.php';
require_once './class/class_mysql.php';
require_once './class/redis.php';
require_once './class/bzyy.php';

$mysql = init_mysql();

$sql = "select id,price from goods ";

$ids = $mysql->getAll($sql);

init_redis();

$redis = $_ENV['redis'];

/*
 * 获取商品在redis队列中的用户数
 */

//获取队列中的商品信息
foreach($ids as $v){
	$key = 'queue_goods_'. $v['id'];

	//获取商品用户队列
	$queue_goods = $redis->lrange($key,0,-1);
	var_dump($queue_goods);
	
	//获取商品总数量
	$goods_nums = get_goods_num($v['id']);
	var_dump("处理前：".$v['id']."-".$goods_nums);
	
	echo "---------------------------------------------";
	
	//判断数量是否还存在
	if($goods_nums > 0){
		
		if( !empty($queue_goods) ){
			foreach($queue_goods as $user_id){
				
				echo "出队列";
				$redis->lpop($key);
				
				//更新商品队列数量（便于再次添加队列）
				$redis->decr("num_goods_{$v['id']}");
				
				//当前商品总数量
				$current_goods_nums = get_goods_num($v['id']);
				
				if($current_goods_nums <= 0 ){
					//设置用户状态
					$redis->set($user_id,QUEUE_NO_GOODS);
					continue;
				}
				
				//获取用户有效时间
				$user_time = $redis->get($user_id);
				
				if( time()- $user_time > TIMEOUT){
					//如果用户时间超过60秒则删除用户缓存
					$redis->remove($user_id);
				}else{
					//生成订单
					$sql = "INSERT INTO `order` (`user_id`, `goods_id`, `number`, `ctime`, `prrice`, `key`, `sn`, `is_pay`) VALUES (";
					$sql .= "'".uniqid()."',";
					$sql .= $v['id'].","; 
					$sql .= "1,";
					$sql .= "'".time()."',";
					$sql .= "'".$v['price']."',";
					$sql .= "'".$user_id."',";
					$sql .= "'".md5($user_id)."',";  
					$sql .= "'0')";
					
					$mysql->query($sql);
					
					//更新数据库中商品数量
					$mysql->query("UPDATE goods SET store = store-1 WHERE id = {$v['id']}");
					//更新redis中商品数量
					$redis->decr("goods_id:{$v['id']}");
										
					$redis->set($user_id,QUEUE_OK);
				}
				
			}
		}	
	}else{
		$redis->set($key,QUEUE_NO_GOODS);
	}
	
	$goods_nums = get_goods_num($v['id']);
	var_dump("处理后：".$v['id']."-".$goods_nums);
	$queue_goods = $redis->lrange($key,0,-1);
	var_dump($queue_goods);
	echo "---------------------------------------------";
}






